package com.gofunbuy.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.gofunbuy.R;
import com.gofunbuy.app.home.SubTabHomeActivity;
import com.gofunbuy.app.home.HomeActivity;
import com.gofunbuy.app.store.TabStoreActivity;
import com.gofunbuy.core.OrderEntity;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.MediaStore;
import android.util.Log;

public class GoFunBuyUtils {
	public interface GoFunBuyInterface {
		public static final String CONNECTION_RESPONSE = "com.pru.radio.http.response";
		public static final String LOGIN = "login";
		public static final String DOWNLOAD = "download";
		public static final String CHANNEL_LIST = "channel_list";
		public static final String SUBLIST = "sublist";
		public static String TAB_POSE = "tab_pose";
		public static final String BACK_TO_WHO = "back_to_who";
		// 當前需要顯示的tab
		public static final int TAB_HOME = 1;
		public static final int TAB_BOOKING = 2;
		public static final int TAB_MEMBER = 3;
		public static final int TAB_SHOPING = 4;
		public static final int TAB_FAVORABLE = 5;
		public static final int TAB_OHTERS = 6;
		// Handler消息处理
		public static final int MSG_REFRESH_PLAY_SEEKBAR = 1;
		public static final int MSG_REFRESH_SOUND_SEEKBAR = 2;
		public static final int MSG_REFRESH_PLAY_STATE = 3;
		public static final int MSG_REFRESH_SONG_NAME = 4;
		public static final int MSG_LOGIN_STATE = 5;
		public static final int MSG_REFRESH_ADAPTER = 6;
		public static final int MSG_TOAST_INFORMATION = 7;
		public static final int MSG_PLAYER_TEXT_REMIND = 8;
		public static final int MSG_NETWORD_ERROR = 9;
		public static final int MSG_REGIST_STATE = 10;
		public static final int MSG_GET_MESSAGE_STATE = 11;

		// 操作type类型
		public static final int HTTP_LOGIN_OPERATION = 1;
		public static final int HTTP_LIST_OPERATION = 2;
		public static final int HTTP_SUB_LIST_OPERATION = 3;
		public static final int HTTP_FAVORITE_OPERATION = 4;
		public static final int HTTP_DOWNLOAD_OPERATION = 5;

		// 網絡協議中共用的名稱
		public static class ProtocalStatics {

			public static final String LOGIN = "login";
			public static final String ID = "id";
			public static final String USERNAME = "username";
			public static final String NAME = "name";
			public static final String EMAIL = "email";
			public static final String PWD = "password";
			public static final String TEL = "tel";
			public static final String LEVEL = "level";
			public static final String DEP = "dep";
			public static final String SHOPCODE = "shopcode";
			// regist
			public static final String CODE = "code";
			public static final String TEL_CODE = "telcode";
			// donation
			public static final String JP = "jp";
			public static final String DONATION = "donation";
			public static final String USERID = "userid";
			// receipt
			public static final String PRICE = "jp";
			public static final String DATE = "date";
		}

	}

	// 注册包
	public static class RegistXML {
		public String code;
		public String id;
		public String name;
		public String email;
		public String tel;
		public String level;
		public ArrayList<LoginLevelXML> levels;
	}

	public static class LoginLevelXML {
		public String level;
		public String name;
		public String dep = "";
	}

	// 登陸包
	public static class LoginXML {
		public String id;
		public String name;
		public String email;
		public String tel;
		public String level;
		public ArrayList<LoginLevelXML> levels;
	}

	// 购物积分和捐赠包
	public static class IntegrationXML {
		public String jp;
		public String donation;
	}

	// 付款記錄
	public static class PayHistoryXML {
		public String id;
		public String time;
		public String goods;
		public String cost;
		public String integration;
		public String donation;
	}

	public static final String PARAM_SAVE_FILE = "GoFunBuy";
	private static final String TAG = "GoFunBuy";
	public static final int INT_TAB_HOME = 1, INT_TAB_BOOK = 2,
			INT_TAB_MEMBER = 3, INT_TAB_STORE = 4, INT_TAB_FAVOURABLE = 5,
			INT_TAB_OTHER = 6;
	public static final String STRING_TAB_HOME = "home",
			STRING_TAB_BOOK = "book", STRING_TAB_MEMBER = "member",
			STRING_TAB_STORE = "store", STRING_TAB_FAVOURABLE = "favourable",
			STRING_TAB_OTHER = "other";

	public static boolean isSwitchToHome = false;
	public static String mUserID = null;
	public static LoginXML mLoginResult = null;
	public static ArrayList<OrderEntity> mOrders = new ArrayList<OrderEntity>();
	public static AsyncImageLoader2 asyncImageLoader = new AsyncImageLoader2();
	/**
	 * tab 点击事件处理
	 * 
	 * @param a
	 * @param id
	 */
	public static void activateTab(Activity a, int id) {
		switch (id) {
		case INT_TAB_HOME:
			startHomeActivity(a);
			break;
		case INT_TAB_BOOK:
			break;
		case INT_TAB_MEMBER:
			break;
		case INT_TAB_STORE:
			startStoreActivity(a);
			break;
		case INT_TAB_FAVOURABLE:
			break;
		case INT_TAB_OTHER:
			break;
		default:
			return;
		}
		// intent.putExtra("withtabs", true);
		// intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		// a.startActivity(intent);
		// a.finish();
		// a.overridePendingTransition(0, 0);
	}

	public static int getIntPref(Context context, String name, int def) {
		SharedPreferences prefs = context.getSharedPreferences(
				context.getPackageName(), Context.MODE_PRIVATE);
		return prefs.getInt(name, def);
	}

	public static void setIntPref(Context context, String name, int value) {
		SharedPreferences prefs = context.getSharedPreferences(
				context.getPackageName(), Context.MODE_PRIVATE);
		Editor ed = prefs.edit();
		ed.putInt(name, value);
		SharedPreferencesCompat.apply(ed);
	}
	public static void setIntPref(Context context, String name, String value) {
		SharedPreferences prefs = context.getSharedPreferences(
				context.getPackageName(), Context.MODE_PRIVATE);
		Editor ed = prefs.edit();
		ed.putString(name, value);
		SharedPreferencesCompat.apply(ed);
	}
	public static String getIntPref(Context context, String name, String def) {
		SharedPreferences prefs = context.getSharedPreferences(
				context.getPackageName(), Context.MODE_PRIVATE);
		return prefs.getString(name,def);
	}
	/**
	 * 启动home当前任务栈中存入最上层的acitivity
	 */
	private static void startHomeActivity(Activity a) {
		Log.v(TAG, "GoFunBuyUtils::startHomeActivity");
		int activityLayoutID = getIntPref(a, GoFunBuyUtils.STRING_TAB_HOME, 0);
		Intent it = new Intent();
		switch (activityLayoutID) {
		case R.layout.sub_home_layout:
			it.setClass(a, SubTabHomeActivity.class);
			break;
		default:
			it.setClass(a, HomeActivity.class);
			break;

		}
		// it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		a.startActivity(it);
		setIntPref(a, STRING_TAB_HOME, activityLayoutID);
		// a.finish();
	}

	/**
	 * 启动store当前任务栈中存入最上层的acitivity
	 */
	private static void startStoreActivity(Activity a) {
		Log.v(TAG, "GoFunBuyUtils::startStoreActivity");
		int activityLayoutID = getIntPref(a, STRING_TAB_STORE, 0);
		Intent it = new Intent();
		switch (activityLayoutID) {
		case R.layout.store_layout:
			it.setClass(a, TabStoreActivity.class);
			break;
		case R.layout.sub_store_layout:
			//it.setClass(a, SubTabStoreReceiptActivity.class);
			break;
		}
		a.startActivity(it);
		setIntPref(a, STRING_TAB_STORE, activityLayoutID);
	}

	public static String SecondsToDate(long mSecond) {
		Date data = new Date(mSecond * 1000);
		SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy	HH:mma");
		// Log.v(TAG,formatter.format(data));
		return formatter.format(data);
	}

	public static boolean isNetworkConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null) {
				return mNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	public static boolean isWifiConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			if (mWiFiNetworkInfo != null) {
				return mWiFiNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	public static boolean isMobileConnected(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mMobileNetworkInfo = mConnectivityManager
					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
			if (mMobileNetworkInfo != null) {
				return mMobileNetworkInfo.isAvailable();
			}
		}
		return false;
	}

	/**
	 * 读取用户名
	 * 
	 * @param context
	 * @return
	 */
	public static String readUsernameFromFile(Context context) {
		SharedPreferences mPreferences = context.getSharedPreferences(
				PARAM_SAVE_FILE, context.MODE_WORLD_READABLE
						| context.MODE_WORLD_WRITEABLE);
		return mPreferences.getString("userName", null);
	}

	/**
	 * 读取密碼
	 * 
	 * @param context
	 * @return
	 */
	public static String readPwdFromFile(Context context) {
		SharedPreferences mPreferences = context.getSharedPreferences(
				PARAM_SAVE_FILE, context.MODE_WORLD_READABLE
						| context.MODE_WORLD_WRITEABLE);
		return mPreferences.getString("pwd", null);
	}

	/**
	 * 写入用户名
	 * 
	 * @param context
	 * @param name
	 */
	public static void writeUsernameToFile(Context context, String name,
			String pwd) {
		SharedPreferences mPreferences = context.getSharedPreferences(
				PARAM_SAVE_FILE, context.MODE_WORLD_READABLE
						| context.MODE_WORLD_WRITEABLE);
		Editor ed = mPreferences.edit();
		ed.putString("userName", name);
		ed.putString("pwd", pwd);
		ed.commit();
	}

	/**
	 * 清楚用户名和密码
	 * 
	 * @param context
	 * @param name
	 */
	public static void clearUsernameAndPwd(Context context) {
		SharedPreferences mPreferences = context.getSharedPreferences(
				PARAM_SAVE_FILE, context.MODE_WORLD_READABLE
						| context.MODE_WORLD_WRITEABLE);
		Editor ed = mPreferences.edit();
		ed.remove("userName");
		ed.remove("pwd");
		ed.commit();
	}

	// 辅助方法，用于把流转换为字符串
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader;
		StringBuilder sb = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}

		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// try {
			// is.close();
			// } catch (IOException e) {
			// e.printStackTrace();
			// }
		}
		// try {
		// // ByteArrayOutputStream os = new ByteArrayOutputStream();
		// byte[] b = new byte[4096];
		// for (int n; (n = is.read(b)) != -1;) {
		// Log.v("111", "" + new String(b, 0, n));
		// // sb.append(new String(b, 0, n) + "\n");
		// // os.write(b, 0, n);
		// }
		// // os.close();
		// // InputStream is_temp = new ByteArrayInputStream(os.toByteArray());
		// // is = is_temp;
		// } catch (IOException e1) {
		//
		// e1.printStackTrace();
		// }
		return sb.toString();
	}

	public static Bitmap Create2DCode(String str) throws WriterException {
		// 生成二维矩阵,编码时指定大小,不要生成了图片以后再进行缩放,这样会模糊导致识别失败
		BitMatrix matrix = new MultiFormatWriter().encode(str,
				BarcodeFormat.QR_CODE, 400, 400);
		int width = matrix.getWidth();
		int height = matrix.getHeight();
		// 二维矩阵转为一维像素数组,也就是一直横着排了
		int[] pixels = new int[width * height];
		for (int y = 0; y < height; y++) {
			for (int x = 0; x < width; x++) {
				if (matrix.get(x, y)) {
					pixels[y * width + x] = 0xff000000;
				}

			}
		}
		Bitmap bitmap = Bitmap.createBitmap(width, height,
				Bitmap.Config.ARGB_8888);
		// 通过像素数组生成bitmap,具体参考api
		bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
		return bitmap;
	}
}
